package com.runen.wnhz.runen.ui.fragment.minem;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.google.gson.Gson;
import com.runen.wnhz.runen.R;
import com.runen.wnhz.runen.bean.UserStarScoreBean;
import com.runen.wnhz.runen.common.utils.NetStateUtils;
import com.runen.wnhz.runen.common.utils.NetUtils;
import com.runen.wnhz.runen.common.utils.OkHttpUtils;
import com.runen.wnhz.runen.common.utils.ToastUtil;
import com.runen.wnhz.runen.di.component.ApplicationComponent;
import com.runen.wnhz.runen.ui.activity.login.LoginForPersonalActivity;
import com.runen.wnhz.runen.ui.activity.major.UserStarActivity;
import com.runen.wnhz.runen.ui.adapter.puadapter.UserStarScoreRecyclerAdapter;
import com.runen.wnhz.runen.ui.fragment.BaseFragment;
import com.runen.wnhz.runen.widget.TitleBuilder;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * Created by Administrator on 2018-04-11.
 */

public class NoticeFragment extends BaseFragment {

    @BindView(R.id.rv_notice)
    RecyclerView rvNotice;
    @BindView(R.id.smart_refresh_layout)
    SmartRefreshLayout smartRefreshLayout;
    Unbinder unbinder;
    @BindView(R.id.text_evaluate)
    TextView textEvaluate;
    private int currentPage = 0;
    private boolean hasNextPage = false;
    private int totalPage = 0;
    private UserStarScoreRecyclerAdapter adapter;
    private List<UserStarScoreBean.DataBean.ListBean> listBeans;
    private boolean isRefresh = false;
    private boolean isLoadMore = false;

    public static NoticeFragment newInstance(String lid) {
        NoticeFragment fragment = new NoticeFragment();
        Bundle bundle = new Bundle();
        bundle.putString("lid", lid);
        fragment.setArguments(bundle);
        return fragment;
    }

    private void getUserScore(String pageNum) {
        String lid = null;
        if(getArguments() != null) {
            lid = getArguments().getString("lid");
        }
        if (lid != null) {
            FormBody formBody = new FormBody.Builder().add("lid", lid).add("page", pageNum).build();
            Request request = new Request.Builder().url(NetUtils.SCORE_USER).post(formBody).build();
            Call newCall = OkHttpUtils.getOkHttpClient().newCall(request);
            newCall.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ToastUtil.showToast("评分数据获取失败");
                            refreshOrLoadMoreFailure();
                        }
                    });
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    try {
                        handleUserStarData(response);
                    } catch (IOException e) {
                        e.printStackTrace();
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ToastUtil.showToast("评分数据请求出现异常");
                                refreshOrLoadMoreFailure();
                            }
                        });
                    }
                }
            });
        }
    }

    private void handleUserStarData(Response response) throws IOException {
        if (response.isSuccessful()) {
            ResponseBody responseBody = response.body();
            final String json = responseBody.string();
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    UserStarScoreBean userStarScoreBean = new Gson().fromJson(json, UserStarScoreBean.class);
                    if ("1".equals(userStarScoreBean.getRe())) {
                        UserStarScoreBean.DataBean dataBean = userStarScoreBean.getData();
                        String isPage = dataBean.getIs_page();
                        if ("1".equals(isPage)) {
                            hasNextPage = true;
                        } else {
                            hasNextPage = false;
                        }
                        totalPage = Integer.parseInt(dataBean.getSum_page());
                        currentPage = Integer.parseInt(dataBean.getPage());
                        List<UserStarScoreBean.DataBean.ListBean> list = dataBean.getList();
                        if (isRefresh) {
                            if (listBeans.size() != 0) {
                                listBeans.clear();
                            }
                            if (list.size() != 0) {
                                currentPage = 0;
                            }
                            listBeans.addAll(list);
                            if (adapter == null) {
                                adapter = new UserStarScoreRecyclerAdapter(getActivity(), listBeans);
                                rvNotice.setAdapter(adapter);
                            } else {
                                adapter.notifyDataSetChanged();
                            }
                            smartRefreshLayout.finishRefresh(true);
                            isRefresh = false;
                            return;
                        }
                        if (isLoadMore) {
                            List<UserStarScoreBean.DataBean.ListBean> list1 = dataBean.getList();
                            if (list1.size() != 0) {
                                currentPage = currentPage + 1;
                            }
                            listBeans.addAll(list1);
                            if (adapter == null) {
                                adapter = new UserStarScoreRecyclerAdapter(getActivity(), listBeans);
                                rvNotice.setAdapter(adapter);
                            } else {
                                adapter.notifyDataSetChanged();
                            }
                            smartRefreshLayout.finishLoadMore(true);
                            isLoadMore = false;
                            return;
                        }
                        currentPage = 0;
                        if (listBeans.size() != 0) {
                            listBeans.clear();
                        }
                        listBeans.addAll(dataBean.getList());
                        adapter = new UserStarScoreRecyclerAdapter(getActivity(), listBeans);
                        rvNotice.setAdapter(adapter);
                    } else if ("0".equals(userStarScoreBean.getRe())) {
                        ToastUtil.showToast(userStarScoreBean.getInfo());
                        refreshOrLoadMoreFailure();
                    } else if ("-1".equals(userStarScoreBean.getRe())) {
                        ToastUtil.showToast(userStarScoreBean.getInfo());
                        startActivity(new Intent(getActivity(), LoginForPersonalActivity.class));
                        refreshOrLoadMoreFailure();
                    }
                }
            });

        }

    }

    @Override
    public void setupAcitivtyComponent(ApplicationComponent appComponent) {

    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (getUserVisibleHint() && getActivity() != null) {
            getUserScore(String.valueOf(currentPage));
        }
    }

    @OnClick({R.id.text_evaluate})
    public void onClickEvent(View view){
        switch (view.getId()){
            case R.id.text_evaluate:
                Intent intent = new Intent(getActivity(), UserStarActivity.class);
                intent.putExtra("lid",getArguments().getString("lid"));
                startActivityForResult(intent,0);
                break;
        }
    }

    @Override
    protected int getLayoutView() {
        return R.layout.notice_fragment_layout;
    }

    @Override
    public void initUiAndListener(View view) {

    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        setListener();
        initData();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == 0 && resultCode == Activity.RESULT_OK){
            boolean submit_star_result = data.getBooleanExtra("submit_star_result", false);
            if(submit_star_result){
                isRefresh = true;
                int tempCurrentPage = 0;
                getUserScore(String.valueOf(tempCurrentPage));
            }
        }
    }

    @Override
    public void initToolBar(TitleBuilder mTitleBuilder) {
        setToolBarVisible(View.GONE);
    }

    @Override
    public void showLoadding() {

    }

    @Override
    public void dimissLoding() {

    }

    private void initData() {
        listBeans = new ArrayList<>();
        rvNotice.setLayoutManager(new LinearLayoutManager(getActivity()));
        rvNotice.addItemDecoration(new HorizontalDividerItemDecoration.Builder(getActivity()).color(Color.parseColor("#eeeeee")).sizeResId(R.dimen.view_height).build());
    }

    private void setListener() {
        smartRefreshLayout.setEnableAutoLoadMore(false);
        smartRefreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (NetStateUtils.isNetworkAvalible(getActivity())) {
                    if (hasNextPage) {
                        int tempCurrentPage = currentPage + 1;
                        isLoadMore = true;
                        getUserScore(String.valueOf(String.valueOf(tempCurrentPage)));
                    } else {
                        ToastUtil.showToast("暂无更多数据");
                        smartRefreshLayout.finishLoadMore(true);
                    }

                } else {
                    ToastUtil.showToast("暂无网络");
                    smartRefreshLayout.finishLoadMore(false);
                }
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                if (NetStateUtils.isNetworkAvalible(getActivity())) {
                    int tempCurrentPage = 0;
                    isRefresh = true;
                    getUserScore(String.valueOf(tempCurrentPage));
                } else {
                    ToastUtil.showToast("暂无网络");
                    smartRefreshLayout.finishRefresh(false);
                }
            }
        });
    }

    private void refreshOrLoadMoreFailure() {
        if (isRefresh) {
            smartRefreshLayout.finishRefresh(false);
            isRefresh = false;
        }
        if (isLoadMore) {
            smartRefreshLayout.finishLoadMore(false);
            isLoadMore = false;
        }
    }

    @Override
    public void showErrorMessage(String msg) {

    }


    @Override
    public void onTitleButtonClicked(TitleBuilder.TitleButton clicked) {

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}
